package com.hue.gulimail.gulimailproduct.service.impl;

import com.hue.gulimail.gulimailproduct.entity.AttrAttrgroupRelationEntity;
import com.hue.gulimail.gulimailproduct.entity.AttrGroupEntity;
import com.hue.gulimail.gulimailproduct.entity.CategoryEntity;
import com.hue.gulimail.gulimailproduct.service.AttrAttrgroupRelationService;
import com.hue.gulimail.gulimailproduct.service.AttrGroupService;
import com.hue.gulimail.gulimailproduct.service.CategoryService;
import com.hue.gulimail.gulimailproduct.vo.AttrResVo;
import com.hue.gulimail.gulimailproduct.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hue.common.utils.PageUtils;
import com.hue.common.utils.Query;

import com.hue.gulimail.gulimailproduct.dao.AttrDao;
import com.hue.gulimail.gulimailproduct.entity.AttrEntity;
import com.hue.gulimail.gulimailproduct.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author yfq
 */
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryByCatId(Long catId, Map<String, Object> params, int attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", attrType);
        if (catId != 0) {
            wrapper.eq("catelog_id", catId);
        }
        Object key = params.get("key");
        if (key != null && !StringUtils.isEmpty(key.toString())) {
            wrapper.and(obj -> obj.eq("attr_id", key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        //将所有的AttrEntity封装为AttrResVo
        List<AttrEntity> records = page.getRecords();
        List<AttrResVo> attrResVos = new ArrayList<>();
        for (AttrEntity attr : records) {
            AttrResVo attrResVo = new AttrResVo();
            BeanUtils.copyProperties(attr, attrResVo);
            //查询分类名
            CategoryEntity catelog = categoryService.getById(attr.getCatelogId());
            attrResVo.setCatelogName(catelog.getName());
            //查询分组名
            QueryWrapper<AttrAttrgroupRelationEntity> relationWrapper = new QueryWrapper<>();
            relationWrapper.eq("attr_id", attr.getAttrId());
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(relationWrapper);
            if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                attrResVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
            attrResVos.add(attrResVo);
        }
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrResVos);
        return pageUtils;
    }

    @Override
    @Transactional
    public void saveAttrAndGroup(AttrVo attrVo) {
        //保存属性信息，并且建立属性和属性分组的关联关系
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        save(attrEntity);
        if (attrVo.getAttrType() == 1) {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attrVo, relation);
            relation.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationService.save(relation);
        }
    }

    @Override
    public AttrResVo getAttrInfo(Long attrId) {
        AttrResVo attrResVo = new AttrResVo();
        //查询attr
        AttrEntity attr = getById(attrId);
        BeanUtils.copyProperties(attr, attrResVo);
        //根据catelogId查询catelogPath
        Long catelogId = attr.getCatelogId();
        List<Long> catelogPath = getCatelogPath(catelogId);
        attrResVo.setCatelogPath(catelogPath);
        //查询attrGroupId
        QueryWrapper<AttrAttrgroupRelationEntity> relationWrapper = new QueryWrapper<>();
        relationWrapper.eq("attr_id", attr.getAttrId());
        AttrAttrgroupRelationEntity relation = attrAttrgroupRelationService.getOne(relationWrapper);
        if (relation != null && relation.getAttrGroupId() != null) {
            AttrGroupEntity attrGroup = attrGroupService.getById(relation.getAttrGroupId());
            attrResVo.setAttrGroupId(attrGroup.getAttrGroupId());
        }
        return attrResVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrResVo attrResVo) {
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(attrResVo, attr);
        updateById(attr);
        //修改分组信息
        QueryWrapper<AttrAttrgroupRelationEntity> relationWrapper = new QueryWrapper<>();
        relationWrapper.eq("attr_id", attr.getAttrId());
        AttrAttrgroupRelationEntity relation = attrAttrgroupRelationService.getOne(relationWrapper);
        relation.setAttrGroupId(attrResVo.getAttrGroupId());
        attrAttrgroupRelationService.updateById(relation);
    }

//    @Override
//    public List<AttrEntity> getByAttrIds(List<Long> attrValueIds) {
//        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
//        wrapper.in("attr_id", attrValueIds);
//        wrapper.eq("search_type", 1);
//        List<AttrEntity> attrs = list(wrapper);
//        return attrs;
//    }

    @Override
    public Set<Long> filterAttrIdBySearchType(List<Long> attrValueIds) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.in("attr_id", attrValueIds);
        wrapper.eq("search_type", 1);
        List<AttrEntity> attrs = list(wrapper);
        return attrs.stream().map(AttrEntity::getAttrId).collect(Collectors.toSet());
    }

    //根据catelogId递归查询catelogPath
    private void getCatelogPath(Long catelogId, List<Long> catelogPath) {
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("cat_id", catelogId);
        CategoryEntity catelog = categoryService.getOne(wrapper);
        Long parentCid = catelog.getParentCid();
        catelogPath.add(catelogId);
        if (parentCid != 0) {
            getCatelogPath(parentCid, catelogPath);
        }
    }

    private List<Long> getCatelogPath(Long catelogId) {
        List<Long> catelogPath = new ArrayList<>();
        getCatelogPath(catelogId, catelogPath);
        List<Long> res = new ArrayList<>();
        //将catelogPath逆序
        for (int i = catelogPath.size() - 1; i >= 0; i--) {
            res.add(catelogPath.get(i));
        }
        return res;
    }
}
